/**
 * Created by tums on 13/8/15.
 */
import TodoStore from './TodoStore.js';
import React,{Component} from 'react';
import TodoAction from './TodoAction.js';

function getTodoState() {
    return {
        allTodos: TodoStore.getAll()
    };
}

export default class TodoApp extends Component {
    constructor(props) {
        super(props);
        this.state = getTodoState();
        this._onChange=this._onChange.bind(this);
        this.onDelete=this.onDelete.bind(this);
        this.onComplete=this.onComplete.bind(this);
    }

    componentDidMount() {
        TodoStore.addChangeListener(this._onChange);
    }

    componentWillUnmount() {
        TodoStore.removeChangeListener(this._onChange);
    }

    render() {
        let todos = this.state.allTodos;
        return (
            <div>
                <header>
                    <a href='#' onClick={this.onCreate.bind(this)}>Create</a>
                    <a href='#' onClick={this.onFilterComplete.bind(this)}>Filter</a>
                </header>
                <table>
                    <colgroup>
                        <col style={{width:'100px'}}/>
                        <col style={{width:'200px'}}/>
                        <col style={{width:'100px'}}/>
                    </colgroup>
                    <thead>
                        <tr>
                            <th>Action</th>
                            <th>Text</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        {Object.keys(todos).map(function (key) {
                            return (<tr data-id={todos[key].id}>
                                <td>
                                    <a href='#' onClick={this.onDelete}>delete</a>
                                    <a href='#' onClick={this.onComplete}>complete</a>
                                </td>
                                <td>{todos[key].text}</td>
                                <td>{todos[key].complete?'complete':'not complete'}</td>
                            </tr>);
                        },this)}
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan='3'>{Object.keys(todos).length}</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        );
    }
    _onChange(){
        this.setState(getTodoState());
    }
    onCreate(){
        TodoAction.create('hello');
    }
    onDelete(e){
        let tr=e.target.closest('tr');
        TodoAction.delete(tr.dataset.id);
    }
    onComplete(e){
        let tr=e.target.closest('tr');
        TodoAction.complete(tr.dataset.id);
    }
    onFilterComplete(){
        TodoAction.filterComplete();
    }
}